package kassiopeia.agent.io;

import javax.annotation.PostConstruct;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Session;
import kassiopeia.commons.io.Message;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

@Component("messageSender")
public class MessageSender {

    private static final Logger logger = Logger.getLogger(MessageSender.class);

    public static final String QUEUE_PREFIX = "AGENT_QUEUE_ID";
    public static final String BROADCAST_TOPIC = "BROADCAST_TOPIC";

    @Autowired
    private ConnectionFactory connectionFactory;

    private JmsTemplate jmsTemplate;

    @PostConstruct
    public void init() {
        jmsTemplate = new JmsTemplate(connectionFactory);
    }

    public void send(Message message, String agentId) {
        sendToDestination(message, new ActiveMQQueue(QUEUE_PREFIX + agentId));
        logger.debug("Sending message: " + message + " to: " + agentId);
    }

    public void broadcast(Message message) {
        sendToDestination(message, new ActiveMQTopic(BROADCAST_TOPIC));
        logger.debug("Broadcasting message: " + message);
    }

    private void sendToDestination(final Message message, Destination destination) {
        try {
            jmsTemplate.send(destination, new MessageCreator() {
                @Override
                public javax.jms.Message createMessage(Session session) throws JMSException {
                    return session.createObjectMessage(message);
                }
            });
        } catch (RuntimeException exception) {
            logger.error("Can't send message via JMS transport! Reason: " + exception + ")");
        }
    }
}
